package com.youlai.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.system.common.request.LayoutSaveRequest;
import com.youlai.system.mapper.LayoutConfigMapper;
import com.youlai.system.model.entity.LayoutConfig;
import com.youlai.system.service.LayoutConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @author Guijiang.Lai
* @description 针对表【layout_config(甯冨眬閰嶇疆琛)】的数据库操作Service实现
* @createDate 2025-08-14 12:15:50
*/
@Service
@Transactional
public class LayoutConfigServiceImpl extends ServiceImpl<LayoutConfigMapper, LayoutConfig>
    implements LayoutConfigService{


    @Autowired
    private LayoutConfigMapper layoutConfigMapper;

    @Override
    public LayoutConfig save(LayoutSaveRequest request) {
        // 获取当前用户ID（从SecurityContext或Session中获取）
        Long currentUserId = getCurrentUserId();

        // 如果设置为默认布局，先取消其他默认布局
        if (Boolean.TRUE.equals(request.getIsDefault())) {
            this.cancelOtherDefaultLayouts(request.getPageName(), currentUserId);
        }

        // 查询是否已存在相同的页面和布局名称组合（且未删除）
        QueryWrapper<LayoutConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", currentUserId);
        queryWrapper.eq("page_name", request.getPageName());
        queryWrapper.eq("layout_name", request.getLayoutName());
        queryWrapper.eq("deleted", 0);

        LayoutConfig existingLayout = layoutConfigMapper.selectOne(queryWrapper);

        // 创建或更新布局配置实体
        LayoutConfig layoutConfig = new LayoutConfig();
        if (existingLayout != null) {
            // 如果存在，则更新
            layoutConfig.setId(existingLayout.getId());
            layoutConfig.setUpdateBy(getCurrentUserName());
        } else {
            // 如果不存在，则新增
            layoutConfig.setUserId(currentUserId);
            layoutConfig.setCreateBy(getCurrentUserName());
        }

        layoutConfig.setPageName(request.getPageName());
        layoutConfig.setLayoutName(request.getLayoutName());
        layoutConfig.setVersion(request.getVersion() != null ? request.getVersion() : "1.0.0");
        layoutConfig.setDescription(request.getDescription());
        layoutConfig.setLayoutData(request.getLayoutData());
        layoutConfig.setIsDefault(request.getIsDefault() != null && request.getIsDefault() ? 1 : 0);
        layoutConfig.setCreateBy(getCurrentUserName());

        // 保存到数据库
        if (existingLayout != null) {
            layoutConfigMapper.updateById(layoutConfig);
        } else {
            layoutConfigMapper.insert(layoutConfig);
        }

        return layoutConfig;
    }

    @Override
    public List<LayoutConfig> getLayoutList(String pageName, String layoutName, Boolean isDefault) {
        QueryWrapper<LayoutConfig> queryWrapper = new QueryWrapper<>();

        // 获取当前用户ID
        Long currentUserId = getCurrentUserId();
        queryWrapper.eq("user_id", currentUserId);
        queryWrapper.eq("deleted", 0);

        // 添加查询条件
        if (pageName != null && !pageName.isEmpty()) {
            queryWrapper.eq("page_name", pageName);
        }
        if (layoutName != null && !layoutName.isEmpty()) {
            queryWrapper.like("layout_name", layoutName);
        }
        if (isDefault != null) {
            queryWrapper.eq("is_default", isDefault ? 1 : 0);
        }

        // 按创建时间倒序排列
        queryWrapper.orderByDesc("create_time");

        return layoutConfigMapper.selectList(queryWrapper);
    }

    @Override
    public LayoutConfig getDefaultLayoutByPage(String pageName) {
        QueryWrapper<LayoutConfig> queryWrapper = new QueryWrapper<>();
        Long currentUserId = getCurrentUserId();

        queryWrapper.eq("user_id", currentUserId);
        queryWrapper.eq("page_name", pageName);
        queryWrapper.eq("is_default", 1);
        queryWrapper.eq("deleted", 0);

        return layoutConfigMapper.selectOne(queryWrapper);
    }

    @Override
    public LayoutConfig getLayoutById(Long id) {
        QueryWrapper<LayoutConfig> queryWrapper = new QueryWrapper<>();
        Long currentUserId = getCurrentUserId();

        queryWrapper.eq("id", id);
        queryWrapper.eq("user_id", currentUserId);
        queryWrapper.eq("deleted", 0);

        return layoutConfigMapper.selectOne(queryWrapper);
    }

    @Override
    public boolean updateLayout(Long id, LayoutSaveRequest request) {
        // 检查布局是否存在且属于当前用户
        LayoutConfig existingLayout = getLayoutById(id);
        if (existingLayout == null) {
            throw new RuntimeException("布局不存在或无权限访问");
        }

        // 如果设置为默认布局，先取消其他默认布局
        if (Boolean.TRUE.equals(request.getIsDefault())) {
            this.cancelOtherDefaultLayouts(request.getPageName(), existingLayout.getUserId());
        }

        // 更新布局配置
        LayoutConfig layoutConfig = new LayoutConfig();
        layoutConfig.setId(id);
        layoutConfig.setLayoutName(request.getLayoutName());
        layoutConfig.setVersion(request.getVersion());
        layoutConfig.setDescription(request.getDescription());
        layoutConfig.setLayoutData(request.getLayoutData());
        layoutConfig.setIsDefault(request.getIsDefault() != null && request.getIsDefault() ? 1 : 0);
        layoutConfig.setUpdateBy(getCurrentUserName());

        int result = layoutConfigMapper.updateById(layoutConfig);
        return result > 0;
    }

    @Override
    public boolean deleteLayout(Long id) {
        // 检查布局是否存在且属于当前用户
        LayoutConfig existingLayout = getLayoutById(id);
        if (existingLayout == null) {
            throw new RuntimeException("布局不存在或无权限访问");
        }

        // 逻辑删除
        int result = layoutConfigMapper.deleteById(id);
        return result > 0;
    }

    @Override
    public boolean setDefaultLayout(Long id) {
        // 检查布局是否存在且属于当前用户
        LayoutConfig existingLayout = getLayoutById(id);
        if (existingLayout == null) {
            throw new RuntimeException("布局不存在或无权限访问");
        }

        // 取消其他默认布局
        this.cancelOtherDefaultLayouts(existingLayout.getPageName(), existingLayout.getUserId());

        // 设置当前布局为默认
        LayoutConfig layoutConfig = new LayoutConfig();
        layoutConfig.setId(id);
        layoutConfig.setIsDefault(1);

        int result = layoutConfigMapper.updateById(layoutConfig);
        return result > 0;
    }

    /**
     * 取消指定页面的其他默认布局
     */
    @Override
    public void cancelOtherDefaultLayouts(String pageName, Long userId) {
        QueryWrapper<LayoutConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("page_name", pageName);
        queryWrapper.eq("is_default", 1);
        queryWrapper.eq("deleted", 0);

        List<LayoutConfig> defaultLayouts = layoutConfigMapper.selectList(queryWrapper);
        for (LayoutConfig layout : defaultLayouts) {
            LayoutConfig updateLayout = new LayoutConfig();
            updateLayout.setId(layout.getId());
            updateLayout.setIsDefault(0);
            layoutConfigMapper.updateById(updateLayout);
        }
    }

    /**
     * 获取当前用户ID
     * 这里需要根据你的用户认证系统来实现
     */
    @Override
    public Long getCurrentUserId() {

        return 1L;
    }

    /**
     * 获取当前用户名
     * 这里需要根据你的用户认证系统来实现
     */
    @Override
    public String getCurrentUserName() {

        return "admin";
    }
}




